<!--
 * 大区端优惠券管理
-->
<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="优惠券名称">
        <el-input v-model="formInline.couponName" placeholder></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status">
          <el-option label="全部" value></el-option>
          <el-option label="启用" value="1"></el-option>
          <el-option label="停用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="search()"
          size="mini"
          >查询</el-button
        >
        <el-button
          type="success"
          plain
          @click="kong()"
          size="mini"
          icon="el-icon-delete"
          >清空</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      border
      :header-cell-style="{ background: '#ebecf0', color: '#606266' }"
      height="600px"
    >
      <el-table-column
        prop="couponSeq"
        label="优惠券编号"
        header-align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="couponName"
        label="优惠券名称"
        header-align="center"
      ></el-table-column>
      <el-table-column label="有效期" header-align="center" width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.validType == '1' || scope.row.validType == '3'"
            >{{ scope.row.validDate
            }}{{ scope.row.validType == '1' ? '天' : '个月' }}</span
          >
          <span v-if="scope.row.validType == '2'"
            >{{ scope.row.validCreateDate }}至{{ scope.row.validEndDate }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="优惠类型" header-align="center">
        <template slot-scope="scope">
          {{ scope.row.discountType == '1' ? '折扣' : '满减' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="couponMoney"
        label="优惠券金额"
        header-align="center"
        align="center"
      >
        <template slot-scope="scope">
          <!-- <span v-if="scope.row.discountType == 0">满{{ scope.row.conponLimitMoney }}减{{
            scope.row.couponMoney
          }}元</span> -->
          <span v-if="scope.row.discountType == 0"
            >{{ scope.row.couponMoney }}元</span
          >
          <span v-else>{{ scope.row.couponDiscount }}折</span>
        </template>
      </el-table-column>
      <el-table-column
        label="已领取数量"
        header-align="center"
        prop="receiveNum"
      ></el-table-column>
      <el-table-column
        label="已分发门店"
        header-align="center"
        align="center"
        width="100px"
      >
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="relatedStore(scope.row)"
            >点击查看</el-button
          >
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" header-align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="#13ce66" :active-value="1" :inactive-value="0"
            @change="updateStatus(scope.row)"></el-switch>
        </template>
      </el-table-column> -->
      <el-table-column
        label="更新时间"
        header-align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" header-align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 1"
            type="text"
            size="mini"
            @click="sendHandle(scope.row)"
            >分发</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100]"
        :current-page="listQuery.current"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <SelectStoreDialog
      :show.sync="showDialog"
      :uuid="curDetail.uuid"
      @refresh="search"
    />

    <el-dialog
      :visible.sync="dialogVisibleShop"
      width="55%"
      @close="closeDialog"
    >
      <template #title>
        {{ `适用门店（共计：${shopList.length || 0}）` }}
        <!-- <el-button type="warning" plain icon="el-icon-delete" size="mini" @click="batchWithdraw">批量撤回</el-button> -->
      </template>
      <el-table
        :data="shopList"
        border
        style="font-size: 10px;width:100%;"
        height="260"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        v-loading="shopListLoading"
        row-key="orgSeq"
      >
        <!-- @selection-change="handleSelectionChange" -->
        <!-- <el-table-column
          type="selection"
          width="55"
          header-align="center"
          align="center"
        ></el-table-column> -->
        <el-table-column
          type="index"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="authCode"
          label="店铺授权码"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="storeName"
          label="门店名称"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="revokeCoupon(scope.row)"
              >撤回</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShop = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryCouponList,
  updateCouponStatus,
  queryCouponById,
  queryStoresByIdAndOrgSeq,
  couponDetachStore,
} from '@/api/promotionProgramEdit';
import SelectStoreDialog from './components/SelectStoreDialog.vue';
import { multiple } from 'webpack-merge';
export default {
  components: {
    SelectStoreDialog,
  },
  data() {
    return {
      formInline: {
        couponName: '',
        status: '',
        upOrgSeq: '',
      },
      tableData: [],
      loading: false,
      total: 0,
      listQuery: {
        current: 1,
        size: 20,
      },
      showDialog: false,
      curDetail: {},

      dialogVisibleShop: false,
      shopList: [],
      shopListLoading: false,

      // 多选
      multipleSelection: [],
    };
  },
  created() {
    const logininfo = localStorage.getItem('logininfo');
    const orgSeq =
      JSON.parse(logininfo).orgSeq || JSON.parse(logininfo).orgList[0].orgSeq;
    this.formInline.upOrgSeq = orgSeq;
    this.couponList();
  },
  methods: {
    search() {
      this.listQuery.current = 1;
      this.couponList();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.couponList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.couponList();
    },
    kong() {
      this.formInline.couponName = '';
      this.formInline.status = '';
    },

    couponList() {
      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          couponType: 2,
          couponName: this.formInline.couponName,
          upOrgSeq: this.formInline.upOrgSeq,
          status: this.formInline.status,
        },
        ascs: [],
        descs: [],
      };
      this.loading = true;
      queryCouponList(data)
        .then((res) => {
          this.tableData = res.records;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    updateStatus(row) {
      row.status = row.status == 1 ? 0 : 1;
      this.$confirm(`是否${row.status == 1 ? '停用' : '启用'}状态?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const data = {
          status: row.status == 1 ? 0 : 1,
          uuid: row.uuid,
        };
        updateCouponStatus(data).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.search();
          } else {
            this.$message.error(res.message || '操作失败');
          }
        });
      });
    },

    sendHandle(row) {
      this.showDialog = true;
      this.curDetail = { ...row };
    },

    relatedStore(row) {
      this.dialogVisibleShop = true;
      this.searchStore(row.uuid);
    },

    // 查询门店列表
    searchStore(uuid) {
      this.shopListLoading = true;
      queryStoresByIdAndOrgSeq({
        uuid,
        upOrgSeq: this.formInline.upOrgSeq,
      })
        .then((res) => {
          this.shopList = res.result.storeDTOS;
        })
        .finally(() => {
          this.shopListLoading = false;
        });
    },

    // 批量撤回选择
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.orgSeq);
    },
    batchWithdraw() {
      this.revokeCoupon(this.multipleSelection);
    },

    // 撤回优惠券
    revokeCoupon(row) {
      this.$confirm(`是否撤回该优惠券?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const data = {
          orgSeqList: Array.isArray(row) ? row : [row.orgSeq],
          couponId: row.couponId,
        };
        couponDetachStore(data).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.searchStore(row.couponId);
          } else {
            this.$message.error(res.message || '操作失败');
          }
        });
      });
    },

    // 关闭弹框
    closeDialog() {
      this.shopList = [];
    },
  },
};
</script>
